package cn.yx.common.web.util;

import cn.hutool.core.util.StrUtil;
import cn.yx.common.core.enums.http.HttpHeaderEnum;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>IP工具类，获取发起HttpServletRequest请求的客户端真实IP地址</p>
 *
 * @author Wgssmart
 */
public final class IpUtil {

    public static final String UNKNOWN = "unknown";

    private IpUtil() {
    }

    /**
     * 根据HttpServletRequest对象获取客户端真实的IP地址
     *
     * @param request HttpServletRequest对象
     * @return
     */
    public static String getIp(HttpServletRequest request) {
        String ip = request.getHeader(HttpHeaderEnum.X_FORWARDED_FOR.getName());
        if (invalidIp(ip)) {
            ip = request.getHeader(HttpHeaderEnum.PROXY_CLIENT_IP.getName());
        }
        if (invalidIp(ip)) {
            ip = request.getHeader(HttpHeaderEnum.WL_PROXY_CLIENT_IP.getName());
        }
        if (invalidIp(ip)) {
            ip = request.getHeader(HttpHeaderEnum.HTTP_CLIENT_IP.getName());
        }
        if (invalidIp(ip)) {
            ip = request.getHeader(HttpHeaderEnum.X_REAL_IP.getName());
        }
        if (invalidIp(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    private static boolean invalidIp(String ip) {
        return StrUtil.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip);
    }

}
